<?php

namespace app\common\model\xiluedu;

use app\common\model\User;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_get;


class MaximComment extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'xiluedu_maxim_comment';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    public static function init() {
        $updateMaximComment = function($row) {
            $maxim_id = $row->maxim_id;
            $count = Db::name('xiluedu_maxim_comment')
                ->where('maxim_id',$maxim_id)
                ->whereNUll('deletetime')
                ->count();
            Db::name('xiluedu_maxim')->where('id',$maxim_id)->update(['comment_count'=>$count]);
        };
        self::afterInsert($updateMaximComment);
        self::afterDelete($updateMaximComment);
    }

    public function user() {
        return $this->belongsTo(User::class, 'user_id')->setEagerlyType(0);
    }

    public function course() {
        return $this->belongsTo('Course', 'maxim_id')->setEagerlyType(0);
    }

    public static function addComment($params) {
//        $hasComment = self::where('user_id',$params['user_id'])
//            ->where('maxim_id', $params['maxim_id'])
//            ->count()>0;
//        if($hasComment) {
//            throw new Exception('您已经发布过评论');
//        }
        try {
            $comment = new self();
            $params['content'] = array_get($params,'content', '');
            $params['status'] = 1;
            $ret = $comment->save($params);
            if ($ret === false) {
                throw new Exception($comment->getError());
            }
            return $comment;
        }catch (\Exception $e) {
            throw $e;
        }

    }
}
